package com.zzcy.bt_print_plugin;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.android.print.sdk.PrinterConstants;
import com.android.print.sdk.PrinterInstance;
import com.android.print.sdk.bluetooth.BluetoothPort;
import com.android.print.sdk.util.Utils;
import com.blankj.utilcode.util.ImageUtils;
import com.zzcy.bt_print_plugin.base.MyAdapter;
import com.zzcy.bt_print_plugin.bean.MessageEvent;
import com.zzcy.bt_print_plugin.utils.ThreadUtil;
import com.zzcy.bt_print_plugin.view.MyTableTextView_Right;
import com.zzcy.bt_print_plugin.view.UnderlineTextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Timer;


public class SearchActivity extends Activity {
    private String TAG = SearchActivity.class.getSimpleName();
    private RecyclerView recyclerView;
    private RelativeLayout rlRefreshBle;
    private RelativeLayout rlTopBar;
    private ImageView ivRefreshBle;
    private ImageView ivBack;
    private MyAdapter adapter;
    private static boolean isConnected;                 //是否已经建立了连接
    private PrinterInstance mPrinter;
    private BluetoothAdapter bluetoothAdapter;
    private LinearLayout mainLinerLayout;
    private LinearLayout llBottom;
    private String printJsonObject;
    private int jsonType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        requestWindowFeature(Window.FEATURE_NO_TITLE);
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL, WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
//        //将对话框的大小按屏幕大小的百分比设置
//        Window window = this.getWindow();
//        WindowManager m = window.getWindowManager();
//        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
//        WindowManager.LayoutParams p = window.getAttributes(); // 3·获取对话框当前的参数值
////        window.setBackgroundDrawable(getResources().getDrawable(R.color.color_333333));
//        p.height = 10; // 高度设置为0
//        p.width = 10; //宽0
//        p.gravity = Gravity.RIGHT;
//        window.setAttributes(p);
        setContentView(R.layout.activity_search);
        Log.e("OkHttp", "onSuccess: 加载进来了");
        rlTopBar = findViewById(R.id.rlTopBar);
        recyclerView = findViewById(R.id.recyclerView);
        rlRefreshBle = findViewById(R.id.rlRefreshBle);
        ivRefreshBle = findViewById(R.id.ivRefreshBle);
        ivBack = findViewById(R.id.ivBack);
        llBottom = findViewById(R.id.llBottom);
        mainLinerLayout = findViewById(R.id.llPrint);
        // 注册eventbus的回调
        EventBus.getDefault().register(this);
        initView();
        initAdapter();
        openBluetooth();
        setOnClick();
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void message(MessageEvent<Object> event) {
        // 前端传递过来的连接的操作
        if (event.getType() == MessageEvent.BLUETOOTH_CONNECT_MESSAGE) {
            JSONObject jsonObject = event.getJsonObject();
            String address = jsonObject.getString("blueToothAddress");
            Log.e("OkHttp", "onSuccess 连接: " + address);
            ThreadUtil.runOnBackThread(() -> {
                try {
                    mAddress = address;
                    mPrinter = new BluetoothPort().btConnnect(SearchActivity.this, address, bluetoothAdapter, mHandler);
                    Utils.saveBtConnInfo(SearchActivity.this, address);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
        }
        // 蓝牙打印传递过来的数据
        if (event.getType() == MessageEvent.BLUETOOTH_PRINTING_MESSAGE) {
            JSONObject jsonObject = event.getJsonObject();
            String content = event.getContent();
            printJsonObject = jsonObject.toString();
            jsonType = Integer.parseInt(content);
            Log.e("OkHttp", jsonType + "--onSuccess: 打印" + printJsonObject);
            jumpType(jsonType);
        }
    }

    private void initView() {
        int actionBarHeight = getActionBarHeight();
        int statusBarHeight = getStatusBarHeight();
        if (statusBarHeight == 0) {
            statusBarHeight = 50;
        }
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(0, statusBarHeight, 0, 0);
        layoutParams.height = actionBarHeight;
        rlTopBar.setLayoutParams(layoutParams);
    }

    // 打印图片
    private void printBitmap(Bitmap bmp) {
        Log.e("OkHttp", "onSuccess: printBitmap==" + (isConnected) + "==" + (mPrinter == null));
        if (!isConnected && mPrinter == null) {
//            BTModule.printFailFunc();
            return;
        }
        Log.e("OkHttp", "onSuccess Handler printBitmap: ");
//        BTModule.printSuccessFunc();
        new Thread() {
            @Override
            public void run() {
                mPrinter.init();
                //设置打印居中
                mPrinter.setPrinter(PrinterConstants.Command.ALIGN, PrinterConstants.Command.ALIGN_CENTER);
                mPrinter.printImage(bmp);
            }
        }.start();
    }

    public interface OnBitmapFinishListener {
        void onFinish(Bitmap bitmap);
    }

    public static Bitmap loadBitmapFromView(View v) {
        if (v == null) {
            return null;
        }

        if (v.getWidth() <= 0 || v.getHeight() <= 0) {
            v.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
            v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
        }

        int width = Math.max(v.getWidth(), 1); // 防止 width 为 0
        int height = Math.max(v.getHeight(), 1); // 防止 height 为 0
        Log.e("OkHttp", "onSuccess:获取屏幕的宽高 " + width + "==" + height);
        Bitmap screenshot = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);
        Canvas canvas = new Canvas(screenshot);
        canvas.translate(-v.getScrollX(), -v.getScrollY());
        canvas.drawColor(Color.WHITE);
        v.draw(canvas);
        return screenshot;
    }

    /**
     * loadBitmapFromView2宽度：0====204231
     * 蓝牙打印失败回调：====
     * 打印报错: width and height must be > 0
     *
     * @param v
     * @return
     */
    public static Bitmap loadBitmapFromView2(final View v) {
        if (v == null) {
            return null;
        }
        // 984====10854   20
        Bitmap screenshot;
        // 0====204231
        Log.e("OkHttp", "onSuccess: loadBitmapFromView2宽度：" + v.getWidth() + "====" + v.getHeight());
        screenshot = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_4444);
        Canvas canvas = new Canvas(screenshot);
        canvas.translate(-v.getScrollX(), -v.getScrollY());//我们在用滑动View获得它的Bitmap时候，获得的是整个View的区域（包括隐藏的），如果想得到当前区域，需要重新定位到当前可显示的区域
        canvas.drawColor(Color.WHITE);
        v.draw(canvas);// 将 view 画到画布上
        return screenshot;
    }

    static DecimalFormat df = new DecimalFormat("0.00");

    public static Bitmap bitmapZoom2(Bitmap mBitmap1, int paperWidth) {
        df = new DecimalFormat("0.00");
        Bitmap mBitmap = mBitmap1;
        int width = 384;
        if (paperWidth == 80) {
            width = 576;
        }
        if (mBitmap.getWidth() >= width) {
            float c = Float.valueOf(df.format((float) mBitmap.getWidth()
                    / width));
            int newHight = Integer.parseInt(new DecimalFormat("0")
                    .format(mBitmap.getHeight() / c));
            mBitmap = zoomImg2(mBitmap, width, newHight);
        } else {
            float c = Float.valueOf(df.format((float) width
                    / mBitmap.getWidth()));
            int newHight1 = Integer.parseInt(new DecimalFormat("0")
                    .format(c * mBitmap.getHeight()));
            mBitmap = zoomImg2(mBitmap, width, newHight1);
        }
        return mBitmap;
    }

    public static Bitmap zoomImg2(Bitmap bm, int newWidth, int newHeight) {
        // 获得图片的宽高
        int width = bm.getWidth();
        int height = bm.getHeight();
        // 计算缩放比例
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;

        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片
        Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix,
                true);
        return newbm;
    }

    //用于接受连接状态消息的 Handler
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case PrinterConstants.Connect.SUCCESS:
                    Log.e("OkHttp", "onSuccess: 蓝牙连接成功 ");
                    isConnected = true;
                    Timer timer = new Timer();
                    myTask = new MyTask();
                    timer.schedule(myTask, 0, 2000);
//                    BTModule.connectSuccessFunc();
//                    LoadingDialog.cancelDialogForLoading();
//                    ToastUtils.showLong("连接成功");
                    break;
                case PrinterConstants.Connect.FAILED:
                case PrinterConstants.Connect.CLOSED:
                    if (myTask != null) {
                        myTask.cancel();
                    }
                    Log.e("OkHttp", "onSuccess: 蓝牙连接关闭 ");
                    isConnected = false;
//                    BTModule.connectSuccessFunc();
//                    LoadingDialog.cancelDialogForLoading();
//                    ToastUtils.showLong("连接失败");
                    break;
                case PrinterConstants.Connect.NODEVICE:
                    Log.e("OkHttp", "onSuccess: 蓝牙连接失败NODEVICE ");
                    isConnected = false;
//                    BTModule.connectFailFunc();
//                    LoadingDialog.cancelDialogForLoading();
//                    ToastUtils.showLong("连接失败");
                    break;
                default:
                    break;
            }
        }
    };

    private String mAddress;

    private void setOnClick() {
        adapter.setOnClickItem(address -> {
//            LoadingDialog.showDialogForLoading(this, "连接中", false);
            ThreadUtil.runOnBackThread(() -> {
                try {
                    mAddress = address;
                    mPrinter = new BluetoothPort().btConnnect(SearchActivity.this, address, bluetoothAdapter, mHandler);
                    Utils.saveBtConnInfo(SearchActivity.this, address);
                } catch (Exception e) {
                    ThreadUtil.runOnUIThread(() -> {
//                        LoadingDialog.cancelDialogForLoading();
//                        ToastUtils.showLong("连接失败");
                    });
                    throw new RuntimeException(e);
                }
            });
        });
        // 刷新请求
        rlRefreshBle.setOnClickListener(v -> {
            openBluetooth();
        });
        ivBack.setOnClickListener(v -> {
            finish();
        });
    }

    private void initAdapter() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        adapter = new MyAdapter();
        recyclerView.setAdapter(adapter);
        // 打印1
        findViewById(R.id.tvBtn1).setOnClickListener(v -> {
            jumpType(1);
        });
        // 打印2
        findViewById(R.id.tvBtn2).setOnClickListener(v -> {
            jumpType(2);
        });
        // 打印3
        findViewById(R.id.tvBtn3).setOnClickListener(v -> {
            jumpType(3);
        });
    }

    /**
     * 获取状态栏高度
     *
     * @return
     */
    private int getStatusBarHeight() {
        Resources resources = getResources();
        int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
        int height = resources.getDimensionPixelSize(resourceId);
        return height;
    }

    public int getActionBarHeight() {
        TypedValue typedValue = new TypedValue();
        int actionBarHeight = 0;
        if (getTheme().resolveAttribute(android.R.attr.actionBarSize, typedValue, true)) {
            actionBarHeight = TypedValue.complexToDimensionPixelSize(typedValue.data, getResources().getDisplayMetrics());
        }
        return actionBarHeight;
    }

    @Override
    protected void onDestroy() {
        //移除蓝牙搜索回调监听器
        EventBus.getDefault().unregister(this);
        super.onDestroy();
        // 解绑
        Log.e("OkHttp", "onSuccess onDestroy 打印了解绑: ");
        unregisterReceiver(bluetoothReceiver);
    }

    // 跳转页面
    private void jumpType(int type) {
//        PrintActivity.startDrawBitmap(this, printJsonObject, type, bitmap -> {
//            printBitmap(bitmap);
//        });
        PrintActivity.startDrawBitmap(this, printJsonObject, type, bitmap -> {
            ImageUtils.save2Album(bitmap, Bitmap.CompressFormat.JPEG);
        });
    }

    String oneJson = "{\n" +
            "    \"title\":\"智海马私人订制抗遗忘\",\n" +
            "\"date\":\"智海马私人订制抗遗忘\",\n" +
            "\"name\":\"智海马私人订制抗遗忘\",\n" +
            "\"dateCycle\":\"智海马私人订制抗遗忘测试换行测试换行\",\n" +
            "    \"type\":1,\n" +
            "    \"data\":[\n" +
            "        {\n" +
            "            \"ChName\":\"猫1\",\n" +
            "            \"EnName\":\"C\"\n" +
            "        },{\n" +
            "            \"ChName\":\"猫2\",\n" +
            "            \"EnName\":\"C\"\n" +
            "        },{\n" +
            "            \"ChName\":\"猫3\",\n" +
            "            \"EnName\":\"C\"\n" +
            "        },{\n" +
            "            \"ChName\":\"猫4\",\n" +
            "            \"EnName\":\"C\"\n" +
            "        },{\n" +
            "            \"ChName\":\"猫5\",\n" +
            "            \"EnName\":\"C\"\n" +
            "        },{\n" +
            "            \"ChName\":\"猫10\",\n" +
            "            \"EnName\":\"C\"\n" +
            "        }\n" +
            "    ]\n" +
            "}";
    String twoJson = "{\n" +
            "    \"title\":\"智海马私人订制抗遗忘\",\n" +
            "    \"data\":[\n" +
            "        {\n" +
            "            \"ChName\":\"猫\",\n" +
            "            \"EnName\":\"Cat\"\n" +
            "        },\n" +
            "        {\n" +
            "            \"ChName\":\"猫\",\n" +
            "            \"EnName\":\"Cat\"\n" +
            "        },\n" +
            "        {\n" +
            "            \"ChName\":\"猫\",\n" +
            "            \"EnName\":\"Cat\"\n" +
            "        },\n" +
            "        {\n" +
            "            \"ChName\":\"猫\",\n" +
            "            \"EnName\":\"Cat\"\n" +
            "        },\n" +
            "        {\n" +
            "            \"ChName\":\"猫\",\n" +
            "            \"EnName\":\"Cat\"\n" +
            "        },\n" +
            "        {\n" +
            "            \"ChName\":\"猫\",\n" +
            "            \"EnName\":\"Cat\"\n" +
            "        }\n" +
            "    ]\n" +
            "}";
    //    String threeJson = "{\n" +
//            "    \"title\":\"智海马私人订制抗遗忘\",\n" +
//            "\"subheading\":\"副标题\",\n" +
//            "    \"type\":3,\n" +
//            "    \"data\":[\n" +
//            "        {\n" +
//            "            \"ChName\":\"扩展这些刻板印象对人们的影响是很大的。比如，一个穿着钉\",\n" +
//            "            \"EnName\":\"These stereotypes have a strong influence on people. For example\"\n" +
//            "        },{\n" +
//            "            \"ChName\":\"扩展这些刻板印象对人们的影响是很大的。比如，一个穿着钉\",\n" +
//            "            \"EnName\":\"These stereotypes have a strong influence on people. For example\"\n" +
//            "        }\n" +
//            "    ]\n" +
//            "}";
    String threeJson = "{\n" +
            "    \"title\": \"智海马私人订制\",\n" +
            "    \"type\": 3,\n" +
            "    \"subheading\": \"Work hard\",\n" +
            "    \"data\": \"[{\\\"ChName\\\":\\\"亲爱的同学们,\\\",\\\"EnName\\\":\\\"Dear students,\\\"},{\\\"ChName\\\":\\\"早上好/下午好/晚上好!\\\",\\\"EnName\\\":\\\"Good morning/afternoon/evening!\\\"},{\\\"ChName\\\":\\\"今天，我想和你们谈谈努力工作和尽力而为的重要性\\\",\\\"EnName\\\":\\\"Today, I want to talk to you about the importance of working hard and trying our best.\\\"},{\\\"ChName\\\":\\\"我们都知道，生活并不总是容易的\\\",\\\"EnName\\\":\\\"As we all know, life is not always easy.\\\"},{\\\"ChName\\\":\\\"一路上会有挑战和困难，但只要努力，我们就能战胜它们，实现我们的目标。\\\",\\\"EnName\\\":\\\"There will be challenges and difficulties along the way, but with hard work, we can beat them and achieve our goals.\\\"},{\\\"ChName\\\":\\\"让我们从“努力”这个词开始\\\",\\\"EnName\\\":\\\"Let's start by talking about the word \\\\\\\"effort.\\\\\\\"\\\"},{\\\"ChName\\\":\\\"努力意味着尽我们最大的努力，付出我们的一切。\\\",\\\"EnName\\\":\\\"Effort means trying our hardest and giving our all.\\\"},{\\\"ChName\\\":\\\"它是关于督促自己做到最好，即使遇到困难也不放弃。\\\",\\\"EnName\\\":\\\"It is about pushing ourselves to do our best and not giving up even when things get tough.\\\"},{\\\"ChName\\\":\\\"我们付出努力时，我们可以完成伟大的事情。\\\",\\\"EnName\\\":\\\"When we put in the effort, we can accomplish great things.\\\"},{\\\"ChName\\\":\\\"想象一下，一个学生有很多作业要做。\\\",\\\"EnName\\\":\\\"Imagine a student who has a lot of homework to do.\\\"},{\\\"ChName\\\":\\\"看起来可能很多，但只要努力，他们就能完成作业，在学习中取得好成绩。\\\",\\\"EnName\\\":\\\"It may seem like a lot, but with effort, they can complete their assignments and do well in their studies.\\\"},{\\\"ChName\\\":\\\"这一切都是关于保持专注，明智地管理我们的时间，不要分心。\\\",\\\"EnName\\\":\\\"It is all about staying focused, managing our time wisely, and not getting distracted.\\\"},{\\\"ChName\\\":\\\"取得成功的另一个重要因素是毅力。\\\",\\\"EnName\\\":\\\"Another important factor in achieving success is perseverance.\\\"},{\\\"ChName\\\":\\\"毅力意味着不放弃，坚持承诺，即使遇到挑战。\\\",\\\"EnName\\\":\\\"Perseverance means not giving up and staying committed, even when things are challenging.\\\"},{\\\"ChName\\\":\\\"它是关于当事情看起来很困难时，要有继续前进的决心\\\",\\\"EnName\\\":\\\"It is about having the determination to keep going when things seem difficult.\\\"},{\\\"ChName\\\":\\\"让我们以一个学生准备比赛为例。\\\",\\\"EnName\\\":\\\"Let's take the example of a student preparing for a competition.\\\"},{\\\"ChName\\\":\\\"他们可能面临激烈的竞争，有时会感到气馁。\\\",\\\"EnName\\\":\\\"They may face tough competition and feel discouraged at times.\\\"},{\\\"ChName\\\":\\\"然而，如果他们继续努力，继续练习和提高他们的技能，他们就能在比赛中取得成功。\\\",\\\"EnName\\\":\\\"However, if they keep trying and continue to practice and improve their skills, they can succeed in the competition.\\\"},{\\\"ChName\\\":\\\"毅力是达到目标的关键。\\\",\\\"EnName\\\":\\\"Perseverance is the key to reaching our goals.\\\"},{\\\"ChName\\\":\\\"此外，有一个积极的态度和相信自己是至关重要的。\\\",\\\"EnName\\\":\\\"Furthermore, it is crucial to have a positive attitude and believe in ourselves.\\\"},{\\\"ChName\\\":\\\"我们不应该让恐惧或自我怀疑阻碍我们前进。\\\",\\\"EnName\\\":\\\"We should not let fear or self-doubt hold us back.\\\"},{\\\"ChName\\\":\\\"相反，我们应该拥抱挑战，把它们视为成长和学习的机会。\\\",\\\"EnName\\\":\\\"Instead, we should embrace challenges and see them as opportunities for growth and learning.\\\"},{\\\"ChName\\\":\\\"记住，成功需要时间和努力。\\\",\\\"EnName\\\":\\\"Remember, it takes time and hard work to achieve success.\\\"},{\\\"ChName\\\":\\\"但只要有决心和努力，我们就能充分发挥我们的潜力，实现我们的梦想。\\\",\\\"EnName\\\":\\\"But with determination and effort, we can reach our full potential and achieve our dreams.\\\"},{\\\"ChName\\\":\\\"总之，我想鼓励你们所有人都要重视努力工作，永远不要停止努力。\\\",\\\"EnName\\\":\\\"In conclusion, I want to encourage all of you to value hard work and never stop trying your best.\\\"},{\\\"ChName\\\":\\\"有了努力、毅力和积极的态度，你就能克服任何障碍，实现你的目标。\\\",\\\"EnName\\\":\\\"With effort, perseverance, and a positive attitude, you can overcome any obstacle and achieve your goals.\\\"},{\\\"ChName\\\":\\\"所以，让我们都努力工作，让我们的梦想成真。\\\",\\\"EnName\\\":\\\"So, let's all work hard and make our dreams come true.\\\"},{\\\"ChName\\\":\\\"谢谢您的关注，祝您生活顺心如意!\\\",\\\"EnName\\\":\\\"Thank you for your attention, and I wish you all the best in your life.\\\"},{\\\"ChName\\\":\\\"真诚地,\\\",\\\"EnName\\\":\\\"Sincerely,\\\"}]\"\n" +
            "}";

    private static final int REQUEST_BLUETOOTH_PERMISSION = 1;
    private static final int REQUEST_ENABLE_BLUETOOTH = 2;

    private void openBluetooth() {
        // 获取 BluetoothAdapter
        BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();

        // 检查设备是否支持蓝牙
        if (bluetoothAdapter == null) {
            Toast.makeText(this, "设备不支持蓝牙", Toast.LENGTH_SHORT).show();
            return;
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
                (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED)) {
            ActivityCompat.requestPermissions(this, new String[]{
                    Manifest.permission.BLUETOOTH,
                    Manifest.permission.BLUETOOTH_ADMIN,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.BLUETOOTH_SCAN
            }, REQUEST_BLUETOOTH_PERMISSION);
        } else {
            startBluetoothDiscovery();
        }
    }


    // 处理权限请求结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQUEST_BLUETOOTH_PERMISSION) {
            boolean allPermissionsGranted = true;
            for (int grantResult : grantResults) {
                if (grantResult != PackageManager.PERMISSION_GRANTED) {
                    allPermissionsGranted = false;
                    break;
                }
            }

            if (allPermissionsGranted) {
                startBluetoothDiscovery();
            } else {
                Toast.makeText(this, "需要蓝牙权限才能搜索设备", Toast.LENGTH_SHORT).show();
            }
        }
    }

    // 开始蓝牙设备搜索
    private void startBluetoothDiscovery() {
        if (!bluetoothAdapter.isEnabled()) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                // 检查是否有BLUETOOTH_CONNECT权限
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                    // 权限未授予，提示用户开启权限
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH_CONNECT}, REQUEST_ENABLE_BLUETOOTH);
                    return;
                }
            }

            // 启动蓝牙开启请求
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BLUETOOTH);
        } else {
            // 注册蓝牙设备扫描的广播接收器
            IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            registerReceiver(bluetoothReceiver, filter);
            Log.e("OkHttp", "onSuccess: 开始搜索了");
            if (bluetoothAdapter.isDiscovering()) {
                bluetoothAdapter.cancelDiscovery();
            }
            new Handler(Looper.getMainLooper()).postDelayed(() -> {
                bluetoothAdapter.startDiscovery();
            }, 1000); // 延迟 1.5 秒
        }
    }

    // 蓝牙广播接收器，用于处理扫描到的设备
    private final BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//                if (ActivityCompat.checkSelfPermission(SearchActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
//                    Log.e("OkHttp", "onSuccess: 权限被限制了");
//                    return;
//                }
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device.getName() == null)
                    return;
                // 11.29号和客户以及厂家沟通，新加蓝牙名字qidian，之前的蓝牙设备RPP02N，两者都兼容搜索
                if ((device.getName().contains("RPP02N") || device.getName().contains("qidian"))) {
                    //搜索结果
                    Log.e(TAG, "搜索到的设备：" + device.getAddress());
                    adapter.addData(device);
//                    BTModule.invokeBluetoothData(device.getName(), device.getAddress());
                }
            }
        }
    };

    // 处理开启蓝牙的回调结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_ENABLE_BLUETOOTH) {
            if (resultCode == RESULT_OK) {
                // 蓝牙已开启，开始扫描设备
                startBluetoothDiscovery();
            } else {
                Toast.makeText(this, "用户未启用蓝牙", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private MyTask myTask;

    /**
     * wifi机器需要定时读取打印机数据, 如下代码
     * 当连接断开时, 读取数据 read() 会触发断开连接的消息
     * <p>
     * USB 蓝牙 可忽略
     */
    private class MyTask extends java.util.TimerTask {
        @Override
        public void run() {
            if (isConnected && mPrinter != null) {
                byte[] by = mPrinter.read();
                if (by != null) {
                    System.out.println(mPrinter.isConnected() + " read byte " + Arrays.toString(by));
                }
            }
        }
    }

}